package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.constant.AlphabetArray;
import com.ysd.lis.entity.SysModule;
import com.ysd.lis.entity.SysParam;
import com.ysd.lis.entity.SysParamField;
import com.ysd.lis.entity.SysParamValue;
import com.ysd.lis.mapper.sys.SysModuleMapper;
import com.ysd.lis.mapper.sys.SysParamFieldMapper;
import com.ysd.lis.mapper.sys.SysParamMapper;
import com.ysd.lis.mapper.sys.SysParamValueMapper;
import com.ysd.lis.request.SysParamParam;
import com.ysd.lis.service.SysParamFieldService;
import com.ysd.lis.service.SysParamService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2022-02-04
 */
@Service
@Slf4j
public class SysParamServiceImpl extends ServiceImpl<SysParamMapper, SysParam> implements SysParamService {
    @Autowired
    SysParamMapper sysParamMapper;
    @Autowired
    SysModuleMapper sysModuleMapper;
    @Autowired
    SysParamFieldMapper sysParamFieldMapper;
    @Autowired
    SysParamValueMapper sysParamValueMapper;

    @Autowired
    SysParamFieldService sysParamFieldService;
    @Autowired
    SysParamValueService sysParamValueService;
    @Override
    public Result findSysParamList(SysParamParam param) {
        LambdaQueryWrapper<SysModule> queryWrapper = new LambdaQueryWrapper<>();
        if(ToolsUtils.isNotEmpty(param.getOrgId())){
            queryWrapper.eq(SysModule::getOrgId, param.getOrgId());
        }
        queryWrapper.eq(SysModule::getDelFlag,0)
                .orderByAsc(SysModule::getSn);
        List<SysModule> moduleList = sysModuleMapper.selectList(queryWrapper);
        LambdaQueryWrapper<SysParam> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysParam::getDelFlag, 0);
        if (StringUtils.isNotBlank(param.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysParam::getName, param.getSeachValue())
                    .or().like(SysParam::getCode, param.getSeachValue()));
        }
        lambdaQueryWrapper.orderByAsc(SysParam::getSeq);
        List<SysParam> sysParamList = sysParamMapper.selectList(lambdaQueryWrapper);

        List<Map>  returnList = new ArrayList<>();
        for(SysModule mo : moduleList){
            Map<String,Object> map = new HashMap();
            map.put("id",mo.getId());
            map.put("name",mo.getName());
            map.put("code",mo.getCode());
            map.put("isModule",true);
            map.put("children",sysParamList.stream().filter(is -> is.getModuleId().equals(mo.getId())).collect(Collectors.toList()));
            returnList.add(map);
        }

        return Result.succ(1, "查询成功", returnList);

    }

    @Override
    public Result addSysParam(SysParam param) {
        //根据code查询表中是否已存在
        LambdaQueryWrapper<SysParam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysParam::getCode, param.getCode())
                .eq(SysParam::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(sysParamMapper.selectList(queryWrapper))) {
            return Result.fail(400, "参数编码已存在", "");
        }
        int insert = sysParamMapper.insert(param);
        if(insert>0){
            return Result.succ(1,"添加成功",param);
        }else {
            return Result.fail(400,"添加失败","");
        }
    }

    @Override
    public Result editSysParam(SysParam param) {
        //查询修改code是否已经存在如果已经存在则不能修改
        LambdaQueryWrapper<SysParam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysParam::getCode, param.getCode())
                .eq(SysParam::getDelFlag, 0)
                .ne(SysParam::getId,param.getId());
        if (ToolsUtils.isNotEmpty(sysParamMapper.selectList(queryWrapper))) {
            return Result.fail(400, "参数编码已存在", "");
        }
        int updateById = sysParamMapper.updateById(param);
        if(updateById>0){
            return Result.succ(1,"修改成功",param);
        }else {
            return Result.fail(400,"修改失败","");
        }
    }

    @Override
    public Result deleteSysParam(SysParam param) {
        LambdaQueryWrapper<SysParamField> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysParamField::getDelFlag, 0)
                .eq(SysParamField::getPid,param.getId());
        Integer cnt = sysParamFieldMapper.selectCount(queryWrapper);
        if (cnt > 0) {
            return Result.fail( "参数下有分组，不能删除");
        }
        int deleteById = sysParamMapper.deleteById(param.getId());
        if(deleteById>0){
            return Result.succ(1, "删除成功", "");
        }else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result copySysParamByOrgId(OrganizationDTO param) {
        String sourceOrgId = param.getSourceOrgId();
        String goalOrgId = param.getGoalOrgId();
        Integer orgIndex = param.getOrgIndex();
        String s = AlphabetArray.Alphabet[orgIndex];
        //根据传过来的goalOrgId删除参数
        sysParamMapper.delete(new LambdaQueryWrapper<SysParam>().eq(SysParam::getOrgId, goalOrgId));
        sysParamFieldMapper.delete(new LambdaQueryWrapper<SysParamField>().eq(SysParamField::getOrgId, goalOrgId));
        sysParamValueMapper.delete(new LambdaQueryWrapper<SysParamValue>().eq(SysParamValue::getOrgId, goalOrgId));
        //根据传过来的sourceOrgId查出所有的参数
        List<SysParam> sysParams = sysParamMapper.selectList(new LambdaQueryWrapper<SysParam>().eq(SysParam::getOrgId, sourceOrgId).eq(SysParam::getDelFlag, 0));
        List<SysParam> addSysParamList = new ArrayList<>();

        for(SysParam sysParam : sysParams){
            SysParam sysParamAdd = new SysParam();
            BeanUtil.copyProperties(sysParam, sysParamAdd, "id", "orgId","moduleId");
            sysParamAdd.setOrgId(goalOrgId);
            String id = sysParam.getId();
            String newId = s + id.substring(s.length());
            sysParamAdd.setId(newId);

            String moduleId = sysParam.getModuleId();
            String newmoduleId = s + moduleId.substring(s.length());
            sysParamAdd.setModuleId(newmoduleId);

            addSysParamList.add(sysParamAdd);
        }
        this.saveBatch(addSysParamList);


        //根据传过来的sourceOrgId查出所有的参数
        List<SysParamField> sysParamFields = sysParamFieldMapper.selectList(new LambdaQueryWrapper<SysParamField>().eq(SysParamField::getOrgId, sourceOrgId).eq(SysParamField::getDelFlag, 0));

        List<SysParamField> addSysParamFieldList = new ArrayList<>();

        for(SysParamField sysParamField : sysParamFields){
            SysParamField sysParamFieldAdd = new SysParamField();
            BeanUtil.copyProperties(sysParamField, sysParamFieldAdd, "id", "orgId","pid");

            sysParamFieldAdd.setOrgId(goalOrgId);

            String id = sysParamField.getId();
            String newId = s + id.substring(s.length());
            sysParamFieldAdd.setId(newId);

            String pid = sysParamField.getPid();
            if(ToolsUtils.isNotEmpty(pid)){
                String newpid = s + pid.substring(s.length());
                sysParamFieldAdd.setPid(newpid);
            }
            addSysParamFieldList.add(sysParamFieldAdd);
        }
        sysParamFieldService.saveBatch(addSysParamFieldList);

        List<SysParamValue> sysParamValues = sysParamValueMapper.selectList(new LambdaQueryWrapper<SysParamValue>().eq(SysParamValue::getOrgId, sourceOrgId).eq(SysParamValue::getDelFlag, 0));

        List<SysParamValue> addSysParamValueList = new ArrayList<>();
        for(SysParamValue sysParamValue : sysParamValues){
            SysParamValue sysParamValueAdd = new SysParamValue();

            BeanUtil.copyProperties(sysParamValue, sysParamValueAdd, "id", "orgId","fieldId","classifyId");

            sysParamValueAdd.setOrgId(goalOrgId);

            String id = sysParamValue.getId();
            String newId = s + id.substring(s.length());
            sysParamValueAdd.setId(newId);

            String fieldId = sysParamValue.getFieldId();
            if(ToolsUtils.isNotEmpty(fieldId)){
                String newparentId = s + fieldId.substring(s.length());
                sysParamValueAdd.setFieldId(newparentId);
            }
            String classifyId = sysParamValue.getClassifyId();
            if(ToolsUtils.isNotEmpty(classifyId)){
                String newparentId = s + classifyId.substring(s.length());
                sysParamValueAdd.setClassifyId(newparentId);
            }

            addSysParamValueList.add(sysParamValueAdd);


        }
        sysParamValueService.saveBatch(addSysParamValueList);


        return Result.succ(1,"复制成功",null);

    }


}
